﻿using System.Collections.Generic;
using System.Linq;
using Preactor.ObjectModel.Interfaces;
using Preactor.ObjectModel.Interfaces.MaterialControl;

namespace Preactor.ObjectModel.Entities
{
    public class MaterialControlStore
    {
        private Dictionary<int, List<int>> InternalSupplies { get; set; }
        private Dictionary<int, List<int>> InternalDemands { get; set; }

        private PreactorObjectModel PreactorObjectModel { get; set; }

        public MaterialControlStore(PreactorObjectModel preactorObjectModel)
        {
            PreactorObjectModel = preactorObjectModel;

            InternalSupplies = preactorObjectModel.GetAllRecords<IOrderLink>().GroupBy(x => x.ToInternalDemandOrder)
                .ToDictionary(x => x.Key, x => x.Where(y => y.FromInternalSupplyOrder != -1).Select(y => y.FromInternalSupplyOrder).ToList());

            InternalDemands = preactorObjectModel.GetAllRecords<IOrderLink>().GroupBy(x => x.FromInternalSupplyOrder)
                .ToDictionary(x => x.Key, x => x.Where(y => y.ToInternalDemandOrder != -1).Select(y => y.ToInternalDemandOrder).ToList());
        }

        public IEnumerable<IOperation> GetInternalSupplyOperationsFor(IOperation operation)
        {
            int id = (int) operation.Id.Value;

            if (InternalSupplies.ContainsKey(id))
            {
                return InternalSupplies[id].Select(x => PreactorObjectModel.GetRecord<IOperation>(new PrimaryKey(x)));
            }
            else
            {
                return Enumerable.Empty<IOperation>();
            }
        }

        public IEnumerable<IOperation> GetInternalDemandOperationsFor(IOperation operation)
        {
            int id = (int)operation.Id.Value;

            if (InternalDemands.ContainsKey(id))
            {
                return InternalDemands[id].Select(x => PreactorObjectModel.GetRecord<IOperation>(new PrimaryKey(x)));
            }
            else
            {
                return Enumerable.Empty<IOperation>();
            }
        }
    }
}
